package com.studentmanagement.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class DatabaseConfig {
    private static final Properties properties = new Properties();
    
    static {
        loadProperties();
    }
    
    private static void loadProperties() {
        try {
            // 首先尝试从外部配置文件加载
            try {
                FileInputStream fis = new FileInputStream("config/database.properties");
                properties.load(fis);
                fis.close();
                System.out.println("从外部配置文件加载数据库配置");
                return;
            } catch (IOException e) {
                // 外部配置不存在，继续尝试其他方式
            }
            
            // 尝试从classpath加载
            try (InputStream is = DatabaseConfig.class.getClassLoader().getResourceAsStream("database.properties")) {
                if (is != null) {
                    properties.load(is);
                    System.out.println("从内部配置文件加载数据库配置");
                    return;
                }
            } catch (IOException e) {
                // 内部配置不存在，继续尝试其他方式
            }
            
            // 最后尝试从系统属性加载
            String dbHost = System.getProperty("db.host", "localhost");
            String dbPort = System.getProperty("db.port", "3306");
            String dbName = System.getProperty("db.name", "student_management");
            String dbUser = System.getProperty("db.user", "root");
            String dbPass = System.getProperty("db.pass", "123456");
            
            properties.setProperty("driver", "com.mysql.cj.jdbc.Driver");
            properties.setProperty("url", String.format("jdbc:mysql://%s:%s/%s?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true", 
                    dbHost, dbPort, dbName));
            properties.setProperty("username", dbUser);
            properties.setProperty("password", dbPass);
            
            System.out.println("从系统属性加载数据库配置");
            
        } catch (Exception e) {
            System.err.println("无法加载数据库配置: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static String getDriver() {
        return properties.getProperty("driver");
    }
    
    public static String getUrl() {
        return properties.getProperty("url");
    }
    
    public static String getUsername() {
        return properties.getProperty("username");
    }
    
    public static String getPassword() {
        return properties.getProperty("password");
    }
    
    public static Properties getProperties() {
        return properties;
    }
} 